package com.heima.user.interceptor;

import com.heima.model.user.pojos.ApUser;

import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {
    /**
     * 获取header中的user信息，并存入当前线程
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到header中的信息
        String userId = request.getHeader("userId");
        Optional<String> optional = Optional.ofNullable(userId);
        if(optional.isPresent()){
            //把用户id存入threadloacl中
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            UserThreadLocalUtil.setUser(apUser);
            log.info("UserTokenFilter设置用户信息到threadlocal中...");
        }
        return true;
    }

    /**
     * 清除线程中的数据
     * @param request
     * @param response
     * @param handler
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理Userthreadlocal...");
        UserThreadLocalUtil.clear();
    }
}
